package com.woniuxy.joylife.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.entity.CenterUser;
import com.woniuxy.common.mapper.CenterUserMapper;
import com.woniuxy.common.utils.KeyUtil;
import com.woniuxy.joylife.manager.VO.AuthVO;
import com.woniuxy.joylife.manager.dao.ManagerDao;
import com.woniuxy.joylife.manager.dao.ManageruserDao;
import com.woniuxy.joylife.manager.dao.OwnerUserDao;
import com.woniuxy.joylife.manager.entity.ManagerEntity;
import com.woniuxy.joylife.manager.entity.ManageruserEntity;
import com.woniuxy.joylife.manager.entity.OwnerUserEntity;
import com.woniuxy.joylife.manager.service.ManagerService;
import com.woniuxy.joylife.manager.service.OwnerUserService;
import com.woniuxy.joylife.manager.utils.PageUtils;
import com.woniuxy.joylife.manager.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service("managerService")
public class ManagerServiceImpl extends ServiceImpl<ManagerDao, ManagerEntity> implements ManagerService {


    @Autowired
    OwnerUserDao ownerUserDao;

    @Autowired
    CenterUserMapper centerUserMapper;

    @Autowired
    ManageruserDao manageruserDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ManagerEntity> page = this.page(
                new Query<ManagerEntity>().getPage(params),
                new QueryWrapper<ManagerEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Boolean checkManager(AuthVO authVO) {
        // 物业信息认证不存在
        ManagerEntity managerEntity = baseMapper.selectOne(
                new QueryWrapper<ManagerEntity>()
                        .eq("name", authVO.getName())
                        .eq("cridential", authVO.getCenterCridentialCode()));
        if (managerEntity==null){
            return false;
        }else {
            // 存储物业账户信息
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(authVO.getId());
            if(centerUser==null){
                return false;
            }
            ManageruserEntity manageruserEntity = new ManageruserEntity();
            manageruserEntity.setUserId(centerUser.getId());
            manageruserEntity.setManagerId(managerEntity.getManagerId());
            manageruserEntity.setManUserId(KeyUtil.generateKey());
            manageruserDao.insert(manageruserEntity);
            return true;
        }
    }

}